/*
 * FileName: HttpSocket2.java
 * Author:   zzw
 * Date:     2018年04月28日
 * Description: http socket
 */
package com.zzw.basic.socket.http;

import java.io.*;
import java.net.ServerSocket;
import java.net.Socket;

/**
 * 〈http socket〉<br>
 * 〈http socket〉
 *
 * @author zzw
 * @see [相关类/方法]（可选）
 * @since [产品/模块版本]（可选）
 */
public class HttpSocket2 {

    private static final String OUTPUT = "<html><head><title>Example</title></head><body><p>Worked!!!</p></body></html>";

    private static final String OUTPUT_HEADERS = "HTTP/1.1 200 OK\r\n" +
            "Content-Type: text/html\r\n" +
            "Content-Length: ";

    private static final String OUTPUT_HEADERS_IOCN = "HTTP/1.1 200 OK\r\n" +
            "Content-Type: image/*\r\n" +
            "Content-Length: ";

    private static final String OUTPUT_END_OF_HEADERS = "\r\n\r\n";

    private static final String Icon_Location = "/Users/macbookpro/Desktop/resizeApi.png";

    public void start() {
        try {
            ServerSocket serverSocket = new ServerSocket(9002);
            boolean isStop = false;
            boolean isIconRequest = false;
            while (!isStop) {
                Socket socket = serverSocket.accept();
                InputStream in = socket.getInputStream();
                BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(in));
                String line = null;
                while ((line = bufferedReader.readLine())!=null){
                    System.out.println(line);
                    if(line.contains("GET /favicon.ico")){
                        sendIcon(Icon_Location , socket);
                        isIconRequest = true;
                    }
                    if (line.isEmpty()) {
                        break;
                    }
                }
                if (!isIconRequest) {
                    sendResponse(socket);
                }

                socket.close();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public void sendResponse(Socket socket) throws IOException {
        OutputStream outputStream = socket.getOutputStream();
        BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(outputStream));
        bw.write(OUTPUT_HEADERS + OUTPUT.length() + OUTPUT_END_OF_HEADERS + OUTPUT);
        bw.flush();
        bw.close();
    }

    public void sendIcon(String iconLocation , Socket socket) throws IOException {
        File file = new File(iconLocation);
        if (!file.exists()) {
            throw new FileNotFoundException();
        }

        BufferedInputStream fileIn = new BufferedInputStream(new FileInputStream(file));
        BufferedOutputStream fileOut = new BufferedOutputStream(socket.getOutputStream());

        fileOut.write(OUTPUT_HEADERS.getBytes());
        fileOut.write(String.valueOf(file.length()).getBytes());
        fileOut.write(OUTPUT_END_OF_HEADERS.getBytes());

        byte[] buf = new byte[1024];
        int size = 0;
        while ((size = fileIn.read(buf))>0){
            fileOut.write(buf , 0 , size);
        }

        fileOut.flush();
        fileOut.close();
        fileIn.close();
    }

    public static void main(String[] args) throws IOException {
        new HttpSocket().start();
    }
}
